package com.yuntsg.nnsfcp.controller.back;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.front.entity.Employee;
import com.yuntsg.nnsfcp.front.entity.TUserRole;
import com.yuntsg.nnsfcp.front.mapper.EmployeeMapper;
import com.yuntsg.nnsfcp.front.mapper.TUserRoleMapper;
import com.yuntsg.nnsfcp.util.AuthCode;
import com.yuntsg.nnsfcp.util.SendSms;
import com.yuntsg.nnsfcp.util.VerifyCodeUtils;
import com.yuntsg.nnsfcp.util.httpclient.SmallTool;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;

//@Api(tags = "登录")
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/login")
public class LoginBackController {


    @Resource
    EmployeeMapper employeeMapper;


    @Resource
    TUserRoleMapper tUserRoleMapper;

    @Resource
    SendSms sendSms;

    @Resource
    HttpSession session;

    @Resource
    HttpServletResponse response;


    @Resource
    HttpServletRequest request;

    //@ApiOperation(value = "生成验证码")
    @GetMapping("/createImage")
    public void createImage(HttpSession session, HttpServletResponse response) {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        String code = VerifyCodeUtils.generateVerifyCode(4);
        SmallTool.printMess(code);
        //存入会话session
        session.setAttribute("imageCode", code.toLowerCase());
        SmallTool.printMess(session.getId());
//        session.setAttribute("sms", 1234);
        //生成图片
        int w = 70, h = 25;
        try {
            VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), code);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 短信验证码
     * */
    @GetMapping("/getsms")
    //@ApiOperation(value = "获取真实短信")

    public void getSms(String phone) {
        List ls = new ArrayList();
        ls.add(phone);
        String s = sendSms.generatorSms(1, ls, "");
        if (!s.equals("")) {
            session.setAttribute("sms", s);
        } else {
            session.setAttribute("sms", 1234);
        }
        //先默认短信验证码
        //暂时默认采取这样的
    }


    /*
     * 短信验证码
     * */
    @GetMapping("/getsms2")
    //@ApiOperation(value = "测试用，是假的 默认是1234")
    public void getSms2(String phone) {
        session.setAttribute("sms", 1234);
//        String s = sendSms.generatorSms(phone);
//        if (!s.equals("")) {
//            session.setAttribute("sms", s);
//        } else {
//
//        }
        //先默认短信验证码
        //暂时默认采取这样的
    }

    @SneakyThrows
    //@ApiOperation(value = "登录", notes = "0:登录成功;1:验证码错误;2:用户名或密码错误;3:短信验证码错误")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", name = "phone", value = "手机号", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "passWord", value = "密码", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "code", value = "验证码", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "sms", value = "手机验证码", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "roleid", value = "角色id", required = true, dataType = "String"),
//            @ApiImplicitParam(paramType = "query", name = "type", value = "类型 1 查收 查引 3 查新", required = true, dataType = "String")
//    })
    @PostMapping("/login")
    public ResultBean<Object> login(String phone, String passWord, String code, Integer type, Integer roleid) {
        Integer flag = 0;
//        String msg = "登录成功";
//        StringBuffer requestURL = request.getRequestURL();
//        String string = requestURL.toString();
//        if (string.contains("gzucm")) {
//            CheckUtil.check(false, "请访问 https://gzycx.yuntsg.com/");
//        }
//        CheckUtil.check(false, "系统迁移维护,大约2024年1月15日开放");
        log.info("type" + type);
        String imageCode = "";
        Employee employee = null;
        String role = "";
        try {
            imageCode = (String) session.getAttribute("imageCode");
        } catch (Exception e) {
        }
        if (code != null && code.toLowerCase().equals(imageCode)) {
            employee = employeeMapper.selectOne(new QueryWrapper<Employee>().eq("mobile", phone));
            CheckUtil.notNull(employee, "用户名不存在");
            //判断当前人员有没有这个角色
            List<Integer> roleIds = tUserRoleMapper.selectList(new QueryWrapper<TUserRole>().eq("user_id", employee.getId())).stream().map(o -> o.getRoleId()).collect(Collectors.toList());
            if (roleIds == null || !roleIds.contains(roleid)) {
                CheckUtil.check(false, "当前登录人员没有此角色 请联系总管理员设置角色");
            }
            String parsePass = AuthCode.encodePass(passWord);
            if (!parsePass.equals(employee.getPassword())) {
                CheckUtil.check(false, "用户密码不对");
            }
            if (employee.getStatus() == 0) {
                CheckUtil.check(false, "该用户已删除，请联系管理员解封");
            }
        } else {
            CheckUtil.check(false, "验证码错误！！！");
        }
//        if (!sms.equals(session.getAttribute("sms"))) {
//            CheckUtil.check(false, "手机验证码不对");
//        }
        //登陆成功后在session记录登陆人的信息和权限
        session.setAttribute("user", employee);
        session.setAttribute("role", 1);
        session.setAttribute("username", employee.getUserName());
        session.setAttribute("uid", employee.getId());
        session.setAttribute("type", type);
        session.setAttribute("roleid", roleid);
        log.info("登录的用户id是" + session.getAttribute("uid"));
        log.info("登录的用户username是" + session.getAttribute("username"));
        return new ResultBean<>(flag);
    }

    @GetMapping("/print-session")
    public void printSession() {
        Enumeration<String> attributeNames = session.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String s = attributeNames.nextElement();
            SmallTool.printMess("++++++++" + s + "的值" + session.getAttribute(s));
        }

    }

    //@ApiOperation(value = "退出")
    @GetMapping("loginout")
    public ResultBean<Object> loginOut(HttpSession session) {
        session.invalidate();
        return new ResultBean<>();
    }
}
